package com.gjy.concurrency.beautiful;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2023-06-13 08:47:40
 */
public class RandomTest {

    private static final Logger log = LoggerFactory.getLogger(RandomTest.class);

    /**
     * 在多线程下使用单个Random实例生成随机数时，当多个线程同时计算随机数来计算新的种子时，多个线程会竞争同一个原子变量的更新操作，
     * 由于原子变量的更新是CAS操作，同时只有一个线程会成功，所以会造成大量线程进行自旋重试，这会降低并发性能，所以ThreadLocalRandom应运而生。
     */
    @Test
    public void test1() {
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            int nextInt = random.nextInt(5);
            log.info("nextInt = {}", nextInt);
        }
    }

    @Test
    public void test2() {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        for (int i = 0; i < 5; i++) {
            int nextInt = random.nextInt(5);
            log.info("nextInt = {}", nextInt);
        }
    }
}
